在現在的應用程序開發中,安全性是不可忽視的重要因素。使用 Spring Security,可以輕鬆地對應用程序進行身份驗證和授權。在這篇文章中,我們將從零開始,設置一個基本的用戶認證系統,讓大家能夠理解和掌握在 Spring Boot 中使用 Spring Security 的基本方法
首先添加依賴
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
這裡我們還添加了 spring-boot-starter-thymeleaf,以便後續使用 Thymeleaf 來生成 HTML 頁面
我們需要創建一個用戶詳細信息服務,這個服務將提供進行身份驗證所需的用戶數據。在 src/main/java/com/example/securitydemo 目錄下創建一個名為 CustomUserDetailsService 的類
@Service
public class CustomUserDetailsService implements UserDetailsService {
    private static final Map<String, String> users = new HashMap<>();
    static {
        // 設置測試用戶的用戶名和密碼
        users.put("user", "password");
        // 可以在此添加其他用戶
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = users.get(username);
        if (password == null) {
            throw new UsernameNotFoundException("用戶未找到");
        }
        return User.withUsername(username).password(password).roles("USER").build();
    }
}
在這段程式碼中,我們創建了一個自定義的用戶詳細信息服務來提供用戶的基本身份驗證數據
接下來,我們需要為應用配置 Spring Security。在相同目錄下創建一個名為 SecurityConfig 的類
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()  // 所有請求都需要身份驗證
                .and()
            .formLogin()  // 使用表單進行登錄
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}
這段程式碼告訴 Spring Security 所有的請求都需要身份驗證,並設置使用表單登錄
我們接下來需要創建一個控制器來處理前端請求。在 src/main/java/com/example/securitydemo 目錄下創建名為 HomeController 的類
@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "home"; // 返回 home.html
    }
    @GetMapping("/login")
    public String login() {
        return "login"; // 返回 login.html
    }
}
這樣就創建了一個基本的用戶驗證,還有HTML的部分這邊就先不多說了,這個範例展示了如何利用 Spring Security 來處理用戶登錄